package com.luochq.nio.c4;

import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

import static com.luochq.nio.c2.ByteBufferUtil.debugAll;

@Slf4j
public class SelectorServer {
    public static void main(String[] args) throws IOException {
        // 1. 创建selector 管理多个channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        // 2. 建立selector 和 channel 的联系 (注册)
        // SelectionKey 就是将来事件发生后 通过它可以知道事件的哪个channel 的事件
        SelectionKey sscKey = ssc.register(selector, 0, null);
        // key 只关注 accept 事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("sscKey : {}", sscKey);
        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            // 3. select 方法， 没有事件发生， 线程阻塞， 有事件， 线程才会恢复运行
            // select 在事件未处理时不会阻塞 事件发生后要么处理 要么取消 不能置之不理
            selector.select();
            // 4. 处理事件, selectionKey 内部包含了所有发生的事件
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); // accept read
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 处理key 时 要从selectionKeys 集合中删除， 否则下次处理就会有问题
                iterator.remove();
                log.debug("key : {}", key);
                // 5. 区分事件类型
                if (key.isAcceptable()) {
                    // 如果是accept
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    SelectionKey scKey = sc.register(selector, 0, buffer);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}", sc);
                    log.debug("scKey : {}", scKey);
                } else if (key.isReadable()) {
                    // 如果是 read
                    try {
                        // 拿到触发事件的channel
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer);
                        if (read == -1) {
                            key.cancel();
                        } else {
//                            buffer.flip();
//                            debugAll(buffer);
//                            System.out.println(Charset.defaultCharset().decode(buffer));
                            split(buffer);
                            // 若需要扩容
                            if (buffer.position() == buffer.limit()) {
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                key.attach(newBuffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }
            }
        }
    }

    private static void split(ByteBuffer buffer) {
        buffer.flip(); // 切换读模式
        for (int i = 0; i < buffer.limit(); i++) {
            if (buffer.get(i) == '\n') {
                int length = i - buffer.position() + 1;
                ByteBuffer nb = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    nb.put(buffer.get());
                }
                debugAll(nb);
            }
        }
        buffer.compact();
    }
}
